package com.xintai.framework.web.service;

import javax.annotation.Resource;

import com.xintai.common.utils.SecurityUtils;
import com.xintai.common.utils.ServletUtils;
import com.xintai.common.utils.StringUtils;
import com.xintai.common.utils.ip.IpUtils;
import com.xintai.framework.manager.AsyncManager;
import com.xintai.system.service.ISysLogininforService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.xintai.common.constant.Constants;
import com.xintai.common.core.domain.model.LoginUser;
import com.xintai.common.core.redis.RedisCache;
import com.xintai.common.exception.CustomException;
import com.xintai.common.exception.user.CaptchaException;
import com.xintai.common.exception.user.CaptchaExpireException;
import com.xintai.common.exception.user.UserPasswordNotMatchException;
import com.xintai.common.utils.MessageUtils;
import com.xintai.framework.manager.factory.AsyncFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author xintai
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysLogininforService iSysLogininforService;

    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public Map login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //判断
        if (!soloLogin)
        {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("UserToken",tokenService.createToken(loginUser));
        map.put("isDifferent",getIpaddr(username));
        // 生成token
        return map;
    }

    /**
     * 判断同一个终端
     * @param userName
     * @return
     */
    private boolean getIpaddr(String userName){
        String loginIp=null;
        String ipAddr = IpUtils.getIpAddr(ServletUtils.getRequest());
        try {
            loginIp = iSysLogininforService.selectLastLogin("登录成功", userName);
        }catch (Exception e){
            e.getMessage();
        }
        if (ipAddr.equals(loginIp)||StringUtils.isEmpty(loginIp)){
            return true;
        }else {
            return false;
        }

    }
}
